package com.qf.service.impl;

import com.qf.dao.SellerMapper;
import com.qf.pojo.entity.Seller;
import com.qf.pojo.entity.Users;
import com.qf.pojo.req.SellerReq;
import com.qf.pojo.resp.BaseResp;
import com.qf.service.SellerService;
import com.qf.utils.Md5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * @ClassName SellerServiceImpl
 * @Description TODO
 * @Author 非乐
 * @Date 2022/10/4 15:10
 * @Version 1.0
 **/
@Service
public class SellerServiceImpl implements SellerService {
    @Autowired
    SellerMapper sellerMapper;

    //    注册邮件发送bean（SpringBoot提供，自动装配时加载）
    @Autowired
    JavaMailSender javaMailSender;

    //    发送源邮箱
    @Value("${spring.mail.username}")
    String from;

    @Override
    public BaseResp register(SellerReq sellerReq, HttpSession session) {
        //        判断用户名是否被注册
        Seller byName = sellerMapper.findByName(sellerReq.getUsername());

//        System.out.println("sellerMapper查询对象："+byName.toString());

        if (byName!=null){
            return new BaseResp(0,"用户名已被注册",null);
        }
//       判断发送验证码的邮箱和验证码
        String email = (String) session.getAttribute("s_email");
        if (!email.equals(sellerReq.getEmail())){
            return new BaseResp(0,"此邮箱未发送验证码",null);
        }

        String code = (String) session.getAttribute("s_code");
        if (!code.equals(sellerReq.getCode())){
            return new BaseResp(0,"验证码错误",null);
        }

        Seller seller = new Seller();
        BeanUtils.copyProperties(sellerReq,seller);
        String pwd= Md5Utils.CreateMd5(seller.getUsername(),seller.getPassword());
        seller.setPassword(pwd);

//        获取店铺最大值
        int maxstoreInfoId = sellerMapper.findMaxstoreInfoId();
        seller.setStoreInfoId(maxstoreInfoId+1);

        int row = sellerMapper.addSeller(seller);
        if (row>0){
            return new BaseResp().SUCCESS();
        }else {
            return new BaseResp().ERROR();
        }
    }

    @Override
    public BaseResp sendEmail(String email,HttpSession session) {
        //        1.判断邮箱是否已经被注册
        Seller byEmail = sellerMapper.findByEmail(email);
        if (byEmail!=null){
            return new BaseResp(0,"邮箱已被注册！",null);
        }

//        2.给指定邮箱发送验证码（创建信息携带体）
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//        设置源邮箱
        simpleMailMessage.setFrom(from);
//        设置目的邮箱
        simpleMailMessage.setTo(email);
//        设置发送主题
        simpleMailMessage.setSubject("注册验证码");
//      设置发送内容（验证码）
        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0;i<4;i++){
            int i1 = new Random().nextInt(10);
            stringBuffer.append(i1);
        }
        simpleMailMessage.setText(stringBuffer.toString());
//        3.发送验证码
        javaMailSender.send(simpleMailMessage);
//        4.将验证码保存在sessin中，供注册验证使用
        session.setAttribute("s_code",stringBuffer.toString());
        session.setAttribute("s_email",email);

        return new BaseResp(200,"验证码发送成功",null);
    }

    @Override
    public BaseResp login(SellerReq sellerReq) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sellerReq.getUsername(), sellerReq.getPassword());

//        验证登录
        try{
            subject.login(token);
        }catch (UnknownAccountException e){
            return new BaseResp(0,"账号不存在",null);
        }catch (IncorrectCredentialsException e){
            return new BaseResp(0,"密码错误",null);
        }

        if (subject.isAuthenticated()){
            Seller byName = sellerMapper.findByName(sellerReq.getUsername());
            return new BaseResp(200,"登录成功",byName);
        }
        else {
            return new BaseResp().ERROR();
        }
    }
}
